import requests
import time
import base64
from configparser import ConfigParser
import codecs
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

cfg = ConfigParser()
cfg.read_file(codecs.open('config.ini', "r", "utf-8-sig"))


def get_token():
    ak = cfg.get('baidu', 'ak')
    sk = cfg.get('baidu', 'sk')
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = dict()
    params['grant_type'] = "client_credentials"
    params['client_id'] = ak
    params['client_secret'] = sk
    response = requests.post(url, params)
    response.encoding = 'utf-8'
    if response.status_code == 200:
        try:
            logger.info("获取token成功")
            return response.json()['access_token']
        except:
            raise AssertionError("获取token失败，请检查ak和sk是否正确", response.text)
    else:
        raise AssertionError("获取token失败", response.json()[''])


def get_api(token, text):
    url = "https://aip.baidubce.com/rpc/2.0/nlp/v1/emotion?charset=UTF-8&access_token=" + token
    headers = {
        'Content-Type': "application/json"
    }
    params = dict()
    params['scene'] = 'talk'
    params['text'] = text
    response = requests.post(url, json=params, headers=headers)
    if response.status_code == 200:
        return response.json()
    else:
        raise AssertionError("请求API失败")





def emotion(text):
    token = get_token()
    response = get_api(token,text)
    l1 = response['items'][0]['label']
    p1= response['items'][0]['prob']
    l2 = response['items'][0]['subitems'][0]['label'] if len( response['items'][0]['subitems']) != 0 else 'neutral'
    p2 = response['items'][0]['subitems'][0]['prob'] if len( response['items'][0]['subitems']) != 0 else 0
    return l1,p1,l2,p2

